package com.ostrich.a2104shopping.ui.user;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ostrich.a2104shopping.R;
import com.ostrich.a2104shopping.databinding.ActivityLoginBinding;
import com.ostrich.lib_common.base.BaseMvvmActivity;
import com.ostrich.lib_common.net.BaseResponseEntity;

@Route(path = "/user/LoginActivity")
public class LoginActivity extends BaseMvvmActivity<LoginViewModel, ActivityLoginBinding> {

    @Override
    public int bindLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {


    }

    @Override
    public void initData() {

    }

    @Override
    public void initListener() {
        binding.btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = binding.etUsername.getText().toString();
                String password = binding.etPassword.getText().toString();

                if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){
                    ToastUtils.showShort("用户名或密码不能为空");
                    return;
                }
                RequestEntity requestEntity = new RequestEntity();
                requestEntity.setUsername(username);
                requestEntity.setPassword(password);
                viewModel.loginjson(requestEntity).observe(LoginActivity.this, new Observer<BaseResponseEntity<UserEntity>>() {
                    @Override
                    public void onChanged(BaseResponseEntity<UserEntity> userEntityBaseResponseEntity) {
                        if(userEntityBaseResponseEntity.getCode() == 200){
                            SPUtils.getInstance().put("login",true);
                            SPUtils.getInstance().put("token",userEntityBaseResponseEntity.getData().getToken());
                            ToastUtils.showShort("登陆成功");
                            finish();
                        }else{
                            ToastUtils.showShort("登陆失败");
                        }
                    }
                });
            }
        });
    }

    @Override
    public void createViewModel() {
        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);
    }
}